package rounte_demo

import (
	"fmt"
	"reflect"
	"time"
)

func makeBond(serialNo int, q chan int) {
	startTime := time.Now()
	fmt.Printf("第%d个任务开始执行，时间: %s\n", serialNo, startTime.String())
	time.Sleep(1 * time.Second)
	fmt.Printf("第%d个任务执行结束，时间%s,耗时: %s\n", serialNo, time.Now().String(), time.Since(startTime).String())
	//将消息放入通道中
	q <- serialNo
	fmt.Printf("第%d个任务发送到channel完成，时间%s\n", serialNo, time.Now().String())
}

func receiveBond(q chan int) {
	time.Sleep(3 * time.Second)
	serialNo := <-q
	fmt.Printf("接收到%d的任务，时间%s\n", serialNo, time.Now().String())
}

func FirstDemo() {
	msgQueue := make(chan int, 5)
	defer close(msgQueue)
	fmt.Println(reflect.TypeOf(msgQueue))
	startTime := time.Now()
	for i := 0; i < 3; i++ {
		//创建协程
		go makeBond(i, msgQueue)
	}
	for i := 0; i < 3; i++ {
		go receiveBond(msgQueue)
	}
	fmt.Printf("整体耗时:%s\n", time.Since(startTime).String())
	time.Sleep(6 * time.Second)
}

func cook(chef, dish string, c chan string) {
	fmt.Printf("厨师%s正在制作%s\n", chef, dish)
	time.Sleep(4 * time.Second)
	c <- fmt.Sprintf("%s[%s]", dish, chef)
}

func CookDemo() {
	cf1 := make(chan string)
	cf2 := make(chan string)
	defer close(cf1)
	defer close(cf2)
	go cook("李大厨", "尻鸭", cf1)
	go cook("王大厨", "生煎", cf2)

	select {
	case dish := <-cf1:
		fmt.Println(dish)
	case dish := <-cf2:
		fmt.Println(dish)
	case ta := <-time.After(2 * time.Second):
		fmt.Println("上菜太慢了", ta)
	}
}

func screw(c chan int) {
	i := 1
	for {
		c <- i
		i++
		time.Sleep(1 * time.Second)
	}
}

func StopDemo() {
	workChan := make(chan int, 100)
	stopChan := make(chan bool)
	defer func() {
		close(workChan)
		close(stopChan)
	}()
	go screw(workChan)
	go func() {
		time.Sleep(10 * time.Second)
		stopChan <- true
	}()

	for {
		select {
		case <-stopChan:
			fmt.Println("下班了")
			return
		case i := <-workChan:
			fmt.Printf("收到第%d个螺丝\n", i)
		}
	}
}
